package com.lh_travel.lohas.activity.webview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.transition.Explode;
import android.transition.Transition;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lh_travel.lohas.R;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.Comment;
import com.lh_travel.lohas.domain.CommentIntentBean;
import com.lh_travel.lohas.utils.ScrPtHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class WebViewActivity extends baseActivity {

    private WebView webview;
    private Toolbar toolbar;
    private ImageButton img_back;
    private RelativeLayout rl_container;
    private ImageButton btn_img;
    private RelativeLayout rl_load;
    private TextView tv_name;
    private TextView tv_date;
    private CommentIntentBean detailBean;
    private ArrayList<Comment> shop;
    private ArrayList<webUrlBean> imgList = new ArrayList<>();
    int shopSize;
    private boolean show;
    private TextView tv_exit;
    private TextView tv_title;
    String referer="";
    private String webTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_webview);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {
        webview = (WebView) findViewById(R.id.webview);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        img_back = (ImageButton) findViewById(R.id.img_back);
        tv_exit = (TextView) findViewById(R.id.tv_exit);
        rl_container = (RelativeLayout) findViewById(R.id.rl_container);
        btn_img = (ImageButton) findViewById(R.id.btn_img);
        rl_load = (RelativeLayout) findViewById(R.id.rl_load);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_date = (TextView) findViewById(R.id.tv_date);
        tv_title = (TextView) findViewById(R.id.tv_title);
    }

    @Override
    public void bindListner() {

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webview.canGoBack()) {

                    webview.goBack();

                } else {
                    finish();
                }
            }
        });

        tv_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btn_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (show) {
                    closePop();

                } else {
                    showpop();
                }

            }
        });

        webview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (show) {
                    closePop();
                }

                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:

                        btn_img.setAlpha(0.7f);

                        break;

                    default:

                        btn_img.setAlpha(1f);

                        break;
                }

                return false;
            }
        });
    }

    @Override
    public void ensureUI() {
        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        detailBean = (CommentIntentBean) getIntent().getSerializableExtra("detailBean");
        shop = (ArrayList<Comment>) getIntent().getSerializableExtra("shop");

        webTitle = detailBean.belong;

        webSetting();
        initLoadView();

        webview.loadUrl(detailBean.url);

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);

                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

        });

        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                super.onProgressChanged(webView, newProgress);

                if (webView.getUrl().contains("m.ctrip")) {
                    btn_img.setImageResource(R.drawable.icon_xiecheng2);

                } else if (webView.getUrl().contains("booking.com")) {
                    btn_img.setImageResource(R.drawable.icon_booking2);

                } else if (webView.getUrl().contains("m.ly.com")) {
                    btn_img.setImageResource(R.drawable.icon_tongcheng2);

                } else if (webView.getUrl().contains("touch.qunar.")) {
                    btn_img.setImageResource(R.drawable.icon_qunaer2);

                } else if (webView.getUrl().contains("m.elong")) {
                    btn_img.setImageResource(R.drawable.icon_yilong2);

                } else if (webView.getUrl().contains("agoda")) {
                    btn_img.setImageResource(R.drawable.icon_ankeda2);

                } else {
                    btn_img.setImageResource(R.drawable.default120);
                }

                if (newProgress == 100) {
                    setLoadGoneAni(400, rl_load, 0, rl_container);
                }
            }
        });
    }

    private void creatPop(View view, String third_id) {

        float viewX = view.getX();
        float viewY = view.getY();

        //----------------------------icon---------------//
        ImageView img_icon = new ImageView(mContext);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        params.width = (int) ScrPtHelper.pt2px(mContext, 96);
        params.height = (int) ScrPtHelper.pt2px(mContext, 96);

        img_icon.setLayoutParams(params);

        int drawableID = 0;

        switch (third_id) {
            case "1": //booking
                drawableID = R.drawable.icon_bingke;
                break;
            case "2": //艺龙
                drawableID = R.drawable.icon_yilong;
                break;
            case "3": //携程
                drawableID = R.drawable.icon_xiecheng;
                break;
            case "4": //agoda
                drawableID = R.drawable.icon_getyourguide;
                break;
            case "6": //同程
                drawableID = R.drawable.icon_tongcheng;
                break;
            case "8": //去哪儿
                drawableID = R.drawable.icon_qunaer;
                break;
        }

        img_icon.setImageDrawable(mContext.getDrawable(drawableID));
        img_icon.setAlpha(0f);

        rl_container.addView(img_icon);

        img_icon.setX(viewX);
        img_icon.setY(viewY - btn_img.getHeight());

        imgList.add(new webUrlBean(img_icon, shop.get(shopSize).third_url));

        img_icon.setVisibility(View.GONE);

        if (shopSize >= shop.size() - 1) {
            return;
        } else {

            ++shopSize;
            creatPop(img_icon, shop.get(shopSize).third_id);
        }
    }


    private void webSetting() {

        WebSettings webSettings = webview.getSettings();
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        //  webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        webSettings.setDomStorageEnabled(true);
        webSettings.setNeedInitialFocus(true);

    }

    private void setLoadGoneAni(int duration, View view, int delay, ViewGroup viewGroup) {
        final Rect viewRect = new Rect();
        rl_load.getLocalVisibleRect(viewRect);
        Transition explode = new Explode();
        explode.setEpicenterCallback(new Transition.EpicenterCallback() {
            @Override
            public Rect onGetEpicenter(Transition transition) {
                return viewRect;
            }
        });

        explode.setDuration(duration);
        explode.setStartDelay(delay);
        explode.setInterpolator(new AccelerateInterpolator());
        TransitionManager.beginDelayedTransition(viewGroup, explode);

        view.setVisibility(View.GONE);

        tv_title.setText(webTitle);
    }

    private void initLoadView() {

        detailBean.checkIn = detailBean.checkIn.replace("-", ".");
        detailBean.checkOut = detailBean.checkOut.replace("-", ".");

        tv_date.setText(detailBean.checkIn + "-" + detailBean.checkOut);

        tv_name.setText(detailBean.keyWord);

        tv_title.setText("您将会通过" + webTitle + "预定...");
    }

    private void showpop() {

        show = true;

        for (int i = 0; i < imgList.size(); i++) {
            final webUrlBean webUrlBean = imgList.get(i);

            webUrlBean.view.setVisibility(View.VISIBLE);

            webUrlBean.view.animate().alpha(1f).setDuration(100).setStartDelay(i * 100).start();

            webUrlBean.view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    webview.loadUrl(webUrlBean.url);
                    closePop();
                }
            });
        }
    }

    private void closePop() {

        show = false;

        for (int i = imgList.size() - 1; i >= 0; i--) {
            webUrlBean webUrlBean = imgList.get(i);

            webUrlBean.view.animate().alpha(0f).setDuration(100).setStartDelay((imgList.size() - i) * 100).start();
            webUrlBean.view.setVisibility(View.GONE);

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (webview != null) {
            webview.clearCache(true);

            webview = null;
        }
    }

    public class webUrlBean implements Serializable {
        public ImageView view;
        public String url;

        public webUrlBean(ImageView view, String url) {
            this.view = view;
            this.url = url;
        }
    }
}
